package com.cqjtu.store.cart.service.impl;

import com.cqjtu.store.address.mapper.AddressMapper;
import com.cqjtu.store.address.pojo.entity.Address;
import com.cqjtu.store.cart.mapper.CartMapper;
import com.cqjtu.store.cart.pojo.dto.CartDTO;
import com.cqjtu.store.cart.pojo.dto.ProductCartDTO;
import com.cqjtu.store.cart.pojo.entity.Cart;
import com.cqjtu.store.common.Constants;
import com.cqjtu.store.order.mapper.OrderItemMapper;
import com.cqjtu.store.order.mapper.OrderMapper;
import com.cqjtu.store.order.pojo.entity.Order;
import com.cqjtu.store.order.pojo.entity.OrderItem;
import com.cqjtu.store.product.mapper.ProductMapper;
import com.cqjtu.store.product.pojo.entity.Product;
import com.cqjtu.store.cart.pojo.vo.CartVO;
import com.cqjtu.store.cart.service.CartService;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional//开始事务
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public List<CartVO> getCartList(UserLoginVO userLoginVO) {
        List<Cart> cartList=cartMapper.getList(userLoginVO.getId());
        if(cartList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户购物车列表为空");
        }
        //将实体类封装的数据转成VO供控制层调用
        List<CartVO> cartVOList=new ArrayList<>();
        cartList.forEach(cart -> {
            CartVO cartVO=new CartVO();
            Product product=productMapper.getById(cart.getProductId());
//            if(product==null){
//                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"商品编号有误，未找到该商品");
//            }
            System.out.println("product==="+product);
            cartVO.setId(cart.getId());
            cartVO.setImage(product.getImage());
            cartVO.setName(product.getTitle());
            cartVO.setPrice(product.getPrice());
            cartVO.setNum(cart.getNum());
            cartVO.setMoney(product.getPrice()*cart.getNum());
            cartVOList.add(cartVO);
        });
        return cartVOList;
    }

    @Override
    public List<CartVO> updateNum(UserLoginVO userLoginVO, CartDTO cartDTO) {
//        Product product=productMapper.getById(cartDTO.getId());
//        if(product==null){
//            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品编号不存在");
//        }
        Integer id=cartDTO.getId();
        if(id==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该购物车编号不能为空");
        }

        Cart cart=cartMapper.getCartById(cartDTO.getId());
        if(cart==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"在购物车内未找到该商品");
        }

        if(cart.getUserId()!=userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有权限进行该操作");
        }

        //开始修改购物车商品数量
        cart.setNum(cartDTO.getNum());
        cart.setModifiedUser(userLoginVO.getUsername());
        System.out.println("cart===="+cart);
        int result=cartMapper.update(cart);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED,"商品数量修改失败");
        }
        List<CartVO> cartVOList = getCartList(userLoginVO);
        return  cartVOList;
    }

    @Override
    public void deleteCart(UserLoginVO userLoginVO, Integer id) {
        Cart cart=cartMapper.getCartById(id);
        if(cart==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"在购物车内未找到该商品，无法删除");
        }
        if(cart.getUserId()!=userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有权限进行该操作");
        }
        //删除
        int result=cartMapper.deleteCart(id);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_DELETE_FAILED,"删除购物车商品失败");
        }
    }

    @Override
    public void deleteCarts(UserLoginVO userLoginVO, List<Integer> ids) {
        ids.forEach(integer -> {
            Cart cart=cartMapper.getCartById(integer);
            if(cart==null){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"在购物车内未找到该商品，无法删除");
            }
            if(cart.getUserId()!=userLoginVO.getId()){
                throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有权限进行该操作");
            }
        });
        int result=cartMapper.deleteCarts(ids);
        Integer flag=ids.size();
        if(result!=flag){
            throw new ServiceException(ServiceCode.ERR_DELETE_FAILED,"批量删除购物车商品失败");
        }
    }

    @Override
    public void addCart(UserLoginVO userLoginVO, Integer productId) {
        Product product=productMapper.getById(productId);
        if(product==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品编号不存在");
        }
        Cart cart=cartMapper.getCartByProductId(userLoginVO.getId(),productId);
        //不在购物车
        if(cart==null){
            cart=new Cart();
            cart.setUserId(userLoginVO.getId());
            cart.setProductId(productId);
            cart.setPrice(product.getPrice());
            cart.setNum(1);
            cart.setCreatedUser(userLoginVO.getUsername());
            int result=cartMapper.addCart(cart);
            if(result!=1) {
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "商品添加购物车失败");
            }
        }
        //已经在购物车—>修改数量
        else{
            cart.setNum(cart.getNum()+1);
            cart.setModifiedUser(userLoginVO.getUsername());
            int result=cartMapper.update(cart);
            if(result!=1) {
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "商品添加购物车失败");
            }
        }
    }

    @Override
    public Integer buy(UserLoginVO userLoginVO, List<CartDTO> cartDTOS) {


        cartDTOS.forEach(cartDTO -> {
            Cart cart= this.cartMapper.getCartById(cartDTO.getId());
            Product byId = this.productMapper.getById(cart.getProductId());
            if (byId.getNum() < cartDTO.getNum()){
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "库存不足");
            }
            byId.setNum(byId.getNum() - cartDTO.getNum());
            int update = this.productMapper.update(byId);
            if (update == 0){
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "修改商品库存失败");
            }
        });
        //添加订单
        Order order=new Order();
        order.setStatus(Constants.NOT_PAY);
        order.setUserId(userLoginVO.getId());

        int sum = 0;
        for (CartDTO dto : cartDTOS) {
            Cart cart = cartMapper.getCartById(dto.getId());
            Product product = productMapper.getById(cart.getProductId());
            int i = product.getPrice() * dto.getNum();
            sum += i;
        }

        order.setTotalPrice(sum);
        order.setCreatedUser(userLoginVO.getUsername());
        order.setIsDelete(Constants.IS_NOT_DELETE);
        int add = this.orderMapper.add(order);
        if (add != 1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "订单添加失败");
        }
        //添加订单项
        cartDTOS.forEach(cartDTO -> {
            OrderItem orderItem=new OrderItem();
            orderItem.setProductId(cartDTO.getId());
            orderItem.setNum(cartDTO.getNum());

            Cart cart=cartMapper.getCartById(cartDTO.getId());
            Product product=productMapper.getById(cart.getProductId());
            orderItem.setProductId(product.getId());
            orderItem.setImage(product.getImage());
            orderItem.setPrice(product.getPrice());
            orderItem.setTitle(product.getTitle());
            orderItem.setCreatedUser(userLoginVO.getUsername());
            orderItem.setOrderId(order.getId());
            int add1 = this.orderItemMapper.add(orderItem);
            if (add1 != 1){
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "订单项添加失败");
            }
            int delete=this.cartMapper.deleteCart(cartDTO.getId());
            if(delete!=1){
                throw new ServiceException(ServiceCode.ERR_DELETE_FAILED,"删除购物车商品失败");
            }
        });
        return order.getId();
    }

    /**
     * 点击在线支付
     * @param aid
     * @param userLoginVO
     * @param oid
     */
    @Override
    public void pay(Integer aid, UserLoginVO userLoginVO, Integer oid) {
        Order orderById = this.orderMapper.getOrderById(oid);
        if (orderById == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "订单不存在");
        }

        //修改订单地址
        Address address = this.addressMapper.getById(aid);
        Order order = new Order();
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setId(orderById.getId());
        order.setZip(String.valueOf(address.getZip()));
        order.setRecvAddress(address.getAddress());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvArea(address.getAreaName());
        order.setRecvCity(address.getCityName());
        order.setModifiedUser(userLoginVO.getUsername());
        int update = this.orderMapper.update(order);
        if (update == 0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "修改失败");
        }
    }

    /**
     *完成支付
     * @param id 订单id
     */
    @Override
    public void alreadyPay(Integer id) {
        Order orderById = this.orderMapper.getOrderById(id);
        if (orderById == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "订单不存在");
        }
        //修改状态为已支付
        int i = this.orderMapper.editStatus(Constants.ALREADY_PAY, id);
        if (i != 1){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "订单修改失败");
        }
        //修改支付时间
        Order order = new Order();
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 将 LocalDateTime 转换为 ZonedDateTime
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = currentTime.atZone(zone);

        // 将 ZonedDateTime 转换为 Instant
        Instant instant = zonedDateTime.toInstant();

        // 将 Instant 转换为 Date
        Date date = Date.from(instant);

        order.setPayTime(date);
        order.setId(id);

        int v = this.orderMapper.update(order);
        if (v == 0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "支付失败");
        }
    }

    @Override
    public void addCarts(UserLoginVO userLoginVO, ProductCartDTO productCartDTO) {
        Product product=productMapper.getById(productCartDTO.getId());
        if(product==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品编号不存在");
        }
        Cart cart=cartMapper.getCartByProductId(userLoginVO.getId(), productCartDTO.getId());
        //不在购物车
        if(cart==null){
            cart=new Cart();
            cart.setUserId(userLoginVO.getId());
            cart.setProductId(productCartDTO.getId());
            cart.setPrice(product.getPrice());
            cart.setNum(productCartDTO.getNum());
            cart.setCreatedUser(userLoginVO.getUsername());
            int result=cartMapper.addCart(cart);
            if(result!=1) {
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "商品添加购物车失败");
            }
        }
        //已经在购物车—>修改数量
        else{
            cart.setNum(cart.getNum()+ productCartDTO.getNum());
            cart.setModifiedUser(userLoginVO.getUsername());
            int result=cartMapper.update(cart);
            if(result!=1) {
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "商品添加购物车失败");
            }
        }
    }


}
